<template>
	<view>
		<!-- 右上角的更多按钮 -->
		<image class="more-icon" @tap="showSheet" src="/static/more.png" mode=""></image>
		<u-action-sheet :actions="sheetList" @select="selectItem" :safeAreaInsetBottom="true"
			:closeOnClickOverlay="true" @close="closeSheet" round=10 cancelText="取消" :closeOnClickAction="true"
			:show="sheetShow"></u-action-sheet>

		<!-- 示例框 -->
		<view class="sample-container">
			<view class="sample-tip">尝试示例：</view>
			<view class="sample-list">
				<block v-for="item in sampleList">
					<view @tap="quickSend(item)" class="sample-item">{{item.content}}</view>
				</block>
			</view>
		</view>
		<!-- 聊天框 -->
		<view class="chat-container">
			<message :talkList="talkList"></message>
		</view>
		<!-- 底部输入框 -->
		<u-tabbar customStyle='height: 134rpx;' :fixed="true" :placeholder="true" :safeAreaInsetBottom="true">
			<view class="typing-container">
				<image v-if="inputType=='keyboard'" class="typing-icon" @tap="switchToSpeech" src="/static/speech.png"
					mode="aspectFill"></image>
				<image v-if="inputType=='speed'" class="typing-icon" @tap="switchToKeyboard" src="/static/keyboard.png"
					mode="aspectFill"></image>
				<view v-if="inputType=='keyboard'" class="typing-text">
					<input v-model="msgContent" :disabled="!AiComplete" :focus="isInputFocus" @blur="onblur"
						@confirm="sendMsg" placeholder="请输入内容" type="text">
				</view>

				<view v-if="inputType=='speed'" @tap="startRecord" @longpress="startRecord" class="typing-text"
					style="display: flex;flex-direction: row;align-items: center;justify-content: center;"><text
						style="font-size: 32rpx;font-weight: 400;">按住 说话</text></view>
				<view class="typing-send" @tap="sendMsg">发送</view>
			</view>
		</u-tabbar>
	</view>
</template>

<script>
	import message from '@/components/message/message.vue';

	const exampleApi = require("@/api/exampleApi");

	const config = require("@/utils/config.js");

	export default {
		components: {
			message
		},
		data() {
			return {
				AiComplete: true, // AI回答是否完成
				functionId: null, // 功能ID（角色ID）
				conversationId: null, // 会话ID
				voicePath: '', // 录音文件路径
				inputType: 'keyboard', // 输入类型，有speed语音输入，keyboard键盘输入
				msgContent: '', // 内容
				isInputFocus: true, // 输入框聚焦
				// 示例列表
				sampleList: [],
				// 菜单列表
				sheetList: [{
						id: 1,
						name: '清空当前'
					},
					{
						id: 2,
						name: '查看历史'
					}
				],
				// 菜单显示
				sheetShow: false,
				aiMessage: '',
				// 聊天列表
				// talkList: [{
				// 	"id": new Date().getTime(),
				// 	"content": '你能干什么',
				// 	"type": 1,
				// 	"pic": "/static/logo.png"
				// }, {
				// 	"id": new Date().getTime(),
				// 	"content": '你好，Bing是一款由微软公司开发的搜索引擎，它可以帮助你搜索互联网上的各种信息，包括新闻、图片、视频、音乐、地图等等。此外，Bing还集成了AI和实时搜索，可以提供更准确和实时的搜索结果。你可以在Bing上输入你感兴趣的关键词，然后点击搜索按钮，Bing会为你提供相关的搜索结果。如果你需要更多帮助，请告诉我你需要搜索什么内容，我会尽力为你提供帮助。',
				// 	"type": 0,
				// 	"pic": "/static/robot.png"
				// }],
				talkList: []
			}
		},
		methods: {
			showSheet() {
				this.sheetShow = true
			},
			closeSheet() {
				this.sheetShow = false
			},
			selectItem(item) {
				console.log(item);
				if (item.id == 1) {
					// 清空记录
					this.talkList = [],
						this.conversationId = null
				}
			},
			doSendMsg(msg) {
				let data = {
					"id": new Date().getTime(),
					"content": msg,
					"type": 1,
					"pic": "/static/logo.png"
				}

				this.talkList.push(data);

				// 标记AI回答为完成,占用输入框
				this.AiComplete = false;

				// 监听连接
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开！');
				});
				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败，请检查！');
					this.AiComplete = true;
				});
				// 发送
				let access = uni.getStorageSync('access') || '';
				let req_data = {
					"token": access,
					"roleId": this.functionId,
					"content": msg,
				}
				if (this.conversationId != null) {
					req_data.conversationId = this.conversationId
				}
				console.log(JSON.stringify(req_data));
				uni.sendSocketMessage({
					data: JSON.stringify(req_data)
				});

				// 接收
				// 追加一个对象,内容是占位符
				this.talkList.push({
					"id": new Date().getTime(),
					"content": '　',
					"type": 0,
					"pic": "/static/robot.png"
				});
				var that = this;
				uni.onSocketMessage(function(res) {
					console.log('收到服务器内容：' + res.data);
					let res_data = JSON.parse(res.data)
					if (res_data.code && res_data.code === 4001) {
						uni.showModal({
							content: res_data.msg,
							complete() {
								uni.navigateTo({
									url: '/pages/loginIn/loginIn'
								});
							}
						})
						return;
					}
					if (res_data.code && res_data.code != 0) {
						uni.showModal({
							content: res_data.msg
						})
						return;
					}
					if (res_data.content) {
						// 去掉占位符
						if (that.talkList[that.talkList.length - 1].content === '　') {
							that.talkList[that.talkList.length - 1].content = ''
						}
						that.talkList[that.talkList.length - 1].content += res_data.content;
					}
					if (res_data.conversationId) {
						that.conversationId = res_data.conversationId;
						that.AiComplete = true;
					}
				});

				this.$nextTick(() => {
					// 滑动到底部
					setTimeout(() => {
						uni.createSelectorQuery().select('.chat-container').boundingClientRect((res) => {
							uni.pageScrollTo({
								scrollTop: res.height + 10,
								duration: 200
							})
						}).exec()
					}, 50)
					// 输入框聚焦
					this.isInputFocus = true;
				})
			},
			sendMsg() {
				if (this.msgContent == '') {
					return;
				}

				this.doSendMsg(this.msgContent)

				// 清空输入框
				this.msgContent = '';
			},
			// 当点击示例
			quickSend(item) {
				this.doSendMsg(item.content)
			},
			// 当输入框失去焦点
			onblur() {
				this.isInputFocus = false;
			},
			switchToSpeech() {
				this.inputType = 'speed';
			},
			switchToKeyboard() {
				this.inputType = 'keyboard';
			},
			startRecord() {
				uni.showModal({
					title: '提示',
					content: '语音暂不兼容H5平台'
				})
				// recorderManager.start();
			},
			endRecord() {
				// recorderManager.stop();
			}
		},
		onLoad(e) {
			console.log(e);
			let functionId = e.functionId;
			this.functionId = functionId;
			// 查询示例
			let reqData = {
				functionId
			}
			exampleApi.listByFunction(reqData).then(res => {
				this.sampleList = res.data
			})

			// 连接
			var url = 'ws://' + config.host + '/chat/conversation/ws'
			console.log(url);
			uni.connectSocket({
				url: url
			});
		}
	}
</script>

<style>
	page {
		background-color: #ebeced;
	}

	.more-icon {
		width: 40rpx;
		height: 40rpx;
		position: fixed;
		right: 34rpx;
		top: 100rpx;
	}

	.sample-container {
		width: 540rpx;
		/* height: 464rpx; */
		border-radius: 16rpx 60rpx 60rpx 60rpx;
		background: #e4e0f0;

		margin-top: 62rpx;
		margin-left: 38rpx;

		padding-bottom: 24rpx;
	}

	.sample-tip {
		font-size: 24rpx;
		font-weight: 400;
		color: #000000;

		padding-top: 24rpx;
		margin-left: 38rpx;
	}

	.sample-list {
		display: flex;
		flex-direction: column;
	}

	.sample-item {
		width: 418rpx;
		/* height: 72rpx; */
		border-radius: 8rpx;
		background: #4B8CF2;

		margin: 18rpx 38rpx;

		font-size: 24rpx;
		font-weight: 400;
		color: #FFFFFF;
		line-height: 50rpx;

		padding: 18rpx;
	}

	.typing-container {
		background-color: #f7f7f7;
		width: 100%;
		height: 134rpx;
		display: flex;
		flex-direction: row;
		align-items: center;

		/* padding: 14rpx 0; */
	}

	.typing-icon {
		width: 56rpx;
		height: 56rpx;

		margin-left: 21rpx;
	}

	.typing-text {
		width: 470rpx;
		height: 76rpx;
		border-radius: 6rpx;
		background: #FFFFFF;

		margin-left: 21rpx;

		padding: 0 16rpx;
	}

	.typing-text>input {
		/* width: 494rpx; */
		height: 76rpx;

		font-size: 32rpx;
	}

	.typing-send {
		width: 112rpx;
		height: 58rpx;
		border-radius: 8rpx;
		background: #07C160;

		text-align: center;
		line-height: 58rpx;

		font-size: 24rpx;
		font-weight: 400;
		color: #FFFFFF;

		margin-left: 21rpx;
	}
</style>